// 基本对话框Controller
class DialogController {
  constructor($scope, $mdDialog) {
    $scope.hide = () => {
      $mdDialog.hide();
    };
    $scope.cancel = () => {
      $mdDialog.cancel();
    };
  }
}

// 创建任务Controller
class TaskDialogController extends DialogController {
  constructor ($scope, $mdDialog, i18n, template) {
    super($scope, $mdDialog);
    $scope.save = (task) => {
      $mdDialog.hide(task);
    }
    $scope.i18n = i18n;

    let task = {
      touser: '',
      template_id: template.template_id,
      data: {},
      url: ''
    };
    let str = template.content;
    str.replace(/{{(.*?).DATA}}/g, (g0, g1) => {
      task.data[g1] = {
        value: '',
        color: '#173177'
      }
    });

    $scope.task = task;
    
  }
}

class TemplateController {
  constructor($scope, $rootScope, $route, $location, $mdMedia, $mdSidenav, $mdDialog, $mdToast, $i18n, $exception, $wechat, $settings, $task, $queue) {
    this.$mdDialog = $mdDialog;
    this.$mdSidenav = $mdSidenav;
    this.$location = $location;
    this.$wechat = $wechat;
    this.$settings = $settings;
    this.$task = $task;
    this.$queue = $queue;
    this.$i18n = $i18n;
    this.$exception = $exception;
    
    $scope.$watch(() => {
      return $mdMedia('xs') || $mdMedia('sm');
    }, (wantsFullScreen) => {
      this.useFullScreen = (wantsFullScreen === true);
    });

    this.$settings.get().then((result) => {
      this.settings = angular.merge({}, result.response);
      console.log(this.settings);
    },
    () => {
      // 设置不存在
      this.showSettings();
    })
  }
  showCreateTask (template) {
    this.$mdDialog.show({
      controller: TaskDialogController,
      templateUrl: '../views/task.dialog.html',
      parent: angular.element(document.body),
      clickOutsideToClose: true,
      locals: {
        i18n: this.$i18n,
        template: template
      },
      fullscreen: this.useFullScreen
    })
    .then((task) => {
      this.$task.put(task).then((result) => {
        console.log(result);
        this.$location.path('messages')
      },
      (error) => {
        this.$exception.handle(error)
      })
    }, () => {

    });
  }
}

TemplateController.$inject = ['$scope', '$rootScope', '$route', '$location', '$mdMedia', '$mdSidenav', '$mdDialog', '$mdToast', '$i18n', '$exception', '$wechat', '$settings', '$task', '$queue'];
angular.module('app').controller('TemplateController', ['$scope', '$rootScope', '$route', '$location', '$mdMedia', '$mdSidenav', '$mdDialog', '$mdToast', '$i18n', '$exception', '$wechat', '$settings', '$task', '$queue', TemplateController]);
